package persistence.javaserialize;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import model.entity.Item;
import model.exceptions.InvalidNameException;
import persistence.ItemsDAO;

import common.Persistence;
import common.Result;
import common.ValueResult;

/**
 * @author tdixon
 * 
 *         Contains methods for retrieving, adding, updating, and deleting items from serialized
 *         java objects.
 */
public class SerialItemsDAO implements ItemsDAO
{

  @SuppressWarnings("unchecked")
  @Override
  public ValueResult<Set<Item>> getAll()
  {
    try
    {
      return new ValueResult<Set<Item>>(true, "", (Set<Item>) Persistence.load("Items"));
    }
    catch (FileNotFoundException e)
    {
      return new ValueResult<Set<Item>>(true, "", new HashSet<Item>());
    }
    catch (Exception e)
    {
      return new ValueResult<Set<Item>>(false, e.getMessage());
    }
  }

  @Override
  public ValueResult<Integer> getCurrentItemBarcodeID()
  {
    try
    {
      return new ValueResult<Integer>(true, "", (Integer) Persistence.load("ItemBarcode"));
    }
    catch (Exception e)
    {
      return new ValueResult<Integer>(false, e.getMessage());
    }
  }

  @Override
  public Result add(Item item)
  {
    return new Result(false, "Not supported for this persistence type; use save instead.");
  }

  @Override
  public Result update(Item item)
  {
    return new Result(false, "Not supported for this persistence type; use save instead.");
  }

  @Override
  public Result delete(Item item)
  {
    return new Result(false, "Not supported for this persistence type; use save instead.");
  }

  @Override
  public Result save(java.util.Set<Item> items)
  {
    try
    {
      Persistence.save(items, "Items");
      return new Result(true);
    }
    catch (IOException | InvalidNameException e)
    {
      return new Result(false, e.getMessage());
    }
  }

  @Override
  public Result saveCurrentItemBarcodeID(int id)
  {
    try
    {
      Persistence.save(id, "ItemBarcode");
      return new Result(true);
    }
    catch (IOException | InvalidNameException e)
    {
      return new Result(false, e.getMessage());
    }
  }
}
